package org.example.supplychain.service;

import org.example.supplychain.domain.Order;
import org.example.supplychain.domain.Supplier;
import org.example.supplychain.mapper.OrderMapper;
import org.example.supplychain.mapper.SupplierMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class SupplierService {

    @Autowired
    private SupplierMapper supplierMapper;

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 添加供应商
     * 传过来一个供应商，插入到数据库中，id索引自增
     *
     * @param supplier 供应商
     */
    public void addSupplier(Supplier supplier) {
        supplierMapper.addSupplier(supplier);
    }

    /**
     * 删除供应商
     * 根据供应商名删除供应商
     *
     * @param supplierName 供应商名
     */
    public void deleteSupplierBySupplierName(String supplierName) {
        supplierMapper.deleteSupplierBySupplierName(supplierName);
    }

    /**
     * 更新供应商
     * 传过来一个供应商实例，更新数据库中的供应商信息
     *
     * @param supplier 供应商
     */
    public void updateSupplier(Supplier supplier) {
        supplierMapper.updateSupplier(supplier);
    }

    /**
     * 根据供应商名获取供应商
     *
     * @param supplierName 供应商名
     * @return 供应商实例
     */
    public Supplier getSupplierBySupplierName(String supplierName) {
        return supplierMapper.getSupplierBySupplierName(supplierName);
    }

    /**
     * 获取所有供应商
     *
     * @return 所有供应商
     */
    public List<Supplier> getAllSuppliers() {
        return supplierMapper.getAllSuppliers();
    }

    /**
     * 根据订单超时率对供应商进行评分
     */
    public void calculateSupplierMark() {
        List<Order> orderList = orderMapper.getAllOrders();
        List<Supplier> supplierList = getAllSuppliers();
        for (Supplier supplier : supplierList) {
            double orderTotal = 0;//订单总数
            double orderPast = 0;//订单超时数
            for (Order order : orderList) {
                if (order.getSupplierName().equals(supplier.getSupplierName())) {
                    orderTotal++;
                    Date date = new Date();
                    if (order.getStatus().equals("进行中") && date.after(order.getDeadline())) {
                        orderPast++;
                    }
                }
            }
            Supplier sp = supplierMapper.getSupplierBySupplierName(supplier.getSupplierName());
            double mark = 10000 * (100 - orderPast / orderTotal);
            mark = Math.round(mark) / 10000.0;
            sp.setMark(mark);
            supplierMapper.updateSupplier(sp);
        }
    }
}
